import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import vuexPersist from "vuex-persist";
export default new Vuex.Store({
  state: {
    history: [],
    celllist: [],
  },
  mutations: {
    sethistory(state, val) {
      if (state.history.length < 5) {
        state.history.unshift(val);
      } else {
        state.history.pop();
        state.history.unshift(val);
      }
    },
    clear(state) {
      state.history = [];
    },
    // add(state, i) {
    //   // state.celllist.push(item);
    //   // let res = state.celllist.filter((item) => {
    //   //   return item.id == i.id;
    //   // });
    //   // if (res.length > 0) {
    //   //   alert("该名著已经收藏过了");
    //   //   return false;
    //   // }
    //   // state.celllist.push(i);
    // },
    // 也可以这么写
    add(state, i) {
      let flag = false;
      state.celllist.forEach((item) => {
        if (item.id == i.id) {
          flag = true;
          alert("该名著已经收藏过了");
        }
      });

      if (flag == false) {
        state.celllist.push(i);
      }
    },
    remove(state, index) {
      state.celllist.splice(index, 1);
    },
    clear(state) {
      state.celllist = [];
    },
  },
  actions: {},
  modules: {},
  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
});
